<template>
    <div class="bottom_div">
        <div class="input_div">
            <pub-image class="speech" :src="isSpeech?'../../static/aimg/img_87.png':'../../static/aimg/img_86.png'"
                @imgClick="chatBottomChange('isSpeech')"></pub-image>
            <all-speech class="speech_btn" v-if="isSpeech" @startRecord="startRecord" @endRecord="endRecord"
                @cancelRecord="cancelRecord"></all-speech>
            <div class="input" v-else>
                <input type="text" placeholder="请输入内容" v-model="content"
                    @keyboardheightchange="contentKeyboardheightchange" @input="contentChange" @blur="contentBlur"
                    :maxlength="-1" />
            </div>
            <pub-image class="more" :src="'../../static/aimg/img_92.png'"
                @imgClick="chatBottomChange('emoteShow')"></pub-image>
            <div v-if="content!=''" class="pub_btn" @click="inputClick">发送</div>
            <pub-image v-if="content==''" class="more" :src="'../../static/aimg/img_12.png'"
                @imgClick="chatBottomChange('toolShow')"></pub-image>
        </div>
        <div class="tool_div" v-if="toolShow">
            <div class="li" v-for="(li, key) in getToolList()" :key="key" @click="toolClick(li)">
                <pub-image class="img" :src="li.icon" :mode="'aspectFit'"></pub-image>
                <div class="txt">{{ li.name }}</div>
            </div>
        </div>
        <scroll-view :scroll-y="true" class="emote_div_scroll" v-if="emoteShow">
            <div class="emote_div">
                <div class="li" v-for="(li, key) in emoteLists" :key="key" @click="emoteClick(li)">
                    <image class="img" mode="aspectFill" :src="li.icon"></image>
                </div>
            </div>
        </scroll-view>
    </div>
</template>

<script>
import { emoteLists } from '@/pages/chat/emote/emote.js';
export default {
    props: {
        chatType: {
            type: Number,
            default: 0
        },
        chatUserInfo: {
            type: Object,
            default: () => ({})
        },
        userInfo: {
            type: Object,
            default: () => ({})
        },
    },
    data() {
        return {
            content: '',//输入框内容
            cursorIndex: 0,//光标位置

            toolShow: false,
            toolList: [
                { name: '相册', icon: '../../static/aimg/img_13.png', chatType: 0 },
                { name: '视频通话', icon: '../../static/aimg/img_14.png', chatType: 1 },
                { name: '语音通话', icon: '../../static/aimg/img_15.png', chatType: 1 },
                { name: '视频', icon: '../../static/aimg/img_16.png', chatType: 0 },
                // { name: '文件', icon: '../../static/aimg/img_17.png' },
                // { name: '转账', icon: '../../static/aimg/img_18.png' }
            ],

            emoteShow: false,//表情框
            emoteLists,

            isSpeech: false,//是否打开语音消息按钮
        };
    },
    onLoad() { },
    methods: {
        getToolList() {
            return this.toolList.filter(li => {
                return li.chatType == 0 || li.chatType == this.chatType;
            })
        },
        // 更新了键盘高度（如果不需要切换表情面板则不用写）
        updateKeyboardHeightChange(res) {
            // if (res.height > 0) {
            //     // 键盘展开，将emojiType设置为emoji
            //     this.toolShow = false;
            // }
        },
        // 用户尝试隐藏键盘，此时如果表情面板在展示中，应当隐藏表情面板，如果是键盘在展示中不用处理，z-paging内部已经处理（如果不需要切换表情面板则不用写）
        hidedKeyboard() {
            // this.toolShow = false;
        },
        inputClick() {
            this.$emit('chatBottomSend', {
                type: 'text',
                content: this.content
            })
            this.content = '';
        },
        toolClick(info) {
            const that = this;
            switch (info.name) {
                case '相册':
                    uni.chooseImage({
                        count: 1, //默认9
                        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['album', 'camera '], //从相册选择
                        success: function (chooseImageRes) {
                            // console.log(JSON.stringify(chooseImageRes.tempFilePaths));
                            // const tempFiles = chooseImageRes.tempFiles;
                            // console.log(chooseImageRes);
                            that.$emit('chatBottomSend', {
                                type: 'image',
                                imageRes: chooseImageRes
                            })
                        },
                    });
                    break;
                case '视频':
                    uni.chooseVideo({
                        sourceType: ['camera', 'album'],
                        success: function (res) {
                            console.log(res);
                            that.$emit('chatBottomSend', {
                                type: 'video',
                                videoInfo: res
                            })
                        }
                    });
                    break;
                case '视频通话':

                    const callParamsVideo = {
                        userID: that.chatUserInfo.userId,
                        callMediaType: 2,   // 1 -- 语音通话，2 -- 视频通话
                        callParams: {
                            roomID: Math.floor(Math.random() * 1000),
                            timeout: 30
                        },
                    };

                    that.$TUICallKit.call(callParamsVideo, res => {
                        console.log('[TUICallKit] call params: ', JSON.stringify(res));
                    });
                    break;
                case '语音通话':
                    const callParams = {
                        userID: that.chatUserInfo.userId,
                        callMediaType: 1,   // 1 -- 语音通话，2 -- 视频通话
                        callParams: {
                            roomID: Math.floor(Math.random() * 1000),
                            timeout: 30
                        },
                    };

                    that.$TUICallKit.call(callParams, res => {
                        console.log('[TUICallKit] call params: ', JSON.stringify(res));
                    });
                    break;
                default:
                    break;
            }
        },
        startRecord() {
            // 开始录音
            console.log('start');
        },
        endRecord(event) {
            // 结束录音并处理得到的录音文件
            // event中，app端仅有tempFilePath字段，微信小程序还有duration和fileSize两个字段

            let tempFilePath = event;
            // #ifdef APP-PLUS
            // tempFilePath = event.tempFilePath;
            // #endif
            if (tempFilePath) {
                console.log('录音结束', tempFilePath);
                this.$emit('chatBottomSend', {
                    type: 'speech',
                    speechSrc: tempFilePath
                })
            } else {
                this.$comFun.toast('录音失败，请稍后再试');
            }
        },
        cancelRecord() {
            // 用户取消录音
            console.log('cancel',);
            this.$comFun.toast('录音取消');
        },
        chatBottomChange(type) {
            if (type && this[type]) {
                this[type] = false;
                return;
            }
            let arr = ['toolShow', 'isSpeech', 'emoteShow'];
            arr.forEach(li => {
                this[li] = li == type ? true : false;
            })
        },
        contentChange(event) {
            this.cursorIndex = event?.detail?.cursor || 0;
        },
        contentKeyboardheightchange() {
            // this.chatBottomChange();
        },
        contentBlur(event) {
            this.cursorIndex = event?.detail?.cursor || 0;
            setTimeout(() => {
                this.cursorIndex = this.content.length;
            }, 10)
        },
        emoteClick(info) {
            let cursorIndex = this.cursorIndex == 0 ? this.content.length : this.cursorIndex;
            let strStart = this.content.substring(0, cursorIndex);
            let strEnd = this.content.slice(cursorIndex);
            this.content = `${strStart}${info.value}${strEnd}`;
            this.cursorIndex = this.content.length;
        }
    },
};
</script>

<style lang="scss" scoped>
@import "@/common/css/chat.scss";
@import "@/pages/chat/emote/emote.scss";
</style>